way1 call xxx.bat
string exefile = @"C:\123.bat"; //exefile="D:\\XX\\xxx.bat"
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(exefile);
psi.UseShellExecute = false;//要讓USER看到cmd畫面就設true
//psi.CreateNoWindow = true;
//psi.RedirectStandardOutput = true;
//psi.RedirectStandardInput = true;
//psi.RedirectStandardError = true;
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
proc.WaitForExit();
if (proc != null)
{
proc.Close();
proc.Dispose();
proc = null;
}
way2 call cmd.exe (和cmd.exe互動)
public string Exec(List<string> commandText)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
string strOutput = null;
try
{
p.Start();
for (int i = 0; i < commandText.Count; i++)
{
string cmd = commandText[i];
p.StandardInput.WriteLine(cmd);
}
p.StandardInput.WriteLine("exit");
strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
strOutput = e.Message;
}
return strOutput;
}